package com.quectel.core.module.grid.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.quectel.constant.core.grid.GridConstant;
import com.quectel.constant.global.SystemConstants;
import com.quectel.core.constants.RedisCacheConstants;
import com.quectel.core.module.grid.dao.GridBindingDao;
import com.quectel.core.module.grid.dao.GridDao;
import com.quectel.core.module.grid.dto.GridDto;
import com.quectel.core.module.grid.entity.GridBindingEntity;
import com.quectel.core.module.grid.entity.GridEntity;
import com.quectel.core.module.grid.service.GridService;
import com.quectel.core.module.really.dto.ReallyCompanyDto;
import com.quectel.core.module.village.dto.VillageBuildingDto;
import com.quectel.core.module.village.dto.VillageDto;
import com.quectel.core.module.village.service.VillageService;
import com.quectel.util.common.CopyUtils;
import com.quectel.util.kit.CacheKit;
import com.quectel.util.kit.Snowflake;
import com.quectel.util.mybatis.MyBatisPlusUtils;
import org.apache.dubbo.config.annotation.DubboService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;
import java.util.function.Consumer;
import java.util.function.Function;

/**
 * @author bob
 * @email bob.yu@quectel.com
 * @date 2023/02/03 15:45
 */
@DubboService
public class GridServiceImpl implements GridService {

    private static final Logger LOGGER = LoggerFactory.getLogger(GridServiceImpl.class);

    /**
     * 入参解释:实体id
     */
    private static final Function<Long, String> GRID_CACHE_BY_ID_FUNC = id -> String.format(RedisCacheConstants.PROJECT_NAME + "GRID_CACHE_BY_ID:%d", id);

    /**
     * 清除缓存方法
     */
    private static final Consumer<GridDto> CLEAR_CACHE_FUNC = dto -> {
        CacheKit.invalidRedisCache(GRID_CACHE_BY_ID_FUNC.apply(dto.getId()));
    };

    @Autowired
    private GridDao gridDao;
    @Autowired
    private GridBindingDao gridBindingDao;
    @Autowired
    private VillageService villageService;


    /**
     * save or update
     * 保存当前对象和相关联的小区
     *
     * @param gridDto
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveOrUpdate(GridDto gridDto) {
        if (gridDto.getId() == null) {
            Long id = save(gridDto);
            gridDto.setId(id);
        } else {
            updateById(gridDto);
        }

        // 删除关联关系 根据网格id删除
        gridBindingDao.delete(new LambdaQueryWrapper<GridBindingEntity>()
                .eq(GridBindingEntity::getGridId, gridDto.getId()));
        for (VillageBuildingDto buildingDto : gridDto.getBuildingList()) {
            GridBindingEntity gridBinding = new GridBindingEntity();
            gridBinding.setId(Snowflake.nextId());
            gridBinding.setGridId(gridDto.getId());
            gridBinding.setSourceType(GridConstant.SourceType.BUILDING.getType());
            gridBinding.setSourceId(buildingDto.getId());
            gridBindingDao.insert(gridBinding);
        }

        for (ReallyCompanyDto reallyCompany : gridDto.getCompanyList()) {
            GridBindingEntity gridBinding = new GridBindingEntity();
            gridBinding.setId(Snowflake.nextId());
            gridBinding.setGridId(gridDto.getId());
            gridBinding.setSourceType(GridConstant.SourceType.COMPANY.getType());
            gridBinding.setSourceId(reallyCompany.getId());
            gridBindingDao.insert(gridBinding);
        }

    }

    @Override
    public GridDto selectCacheById(Long id) {
        return CacheKit.cacheToRedis(
                () -> selectById(id),
                GRID_CACHE_BY_ID_FUNC.apply(id),
                SystemConstants.NOT_NULL_CACHE_EXPIRE_SECONDS
        );
    }

    @Override
    public GridDto selectById(Long id) {
        GridEntity entity = gridDao.selectById(id);
        return paddingField(CopyUtils.copyObj(entity, GridDto.class));
    }

    @Override
    public List<GridDto> queryList(Map<String, Object> params) {
        List<GridEntity> list = gridDao.queryList(params);
        List<GridDto> result = CopyUtils.copyList(list, GridDto.class);
        result.forEach(this::paddingField);
        return result;
    }

    /**
     * 此方法慎用 禁止填充List一类 比如一个人有多个地址这里不允许填充
     * 填充的原则是: 1:被填充对象不经常变换 2:根据id可以走缓存 3数据足够简单 比如设备类型 所属社区等
     *
     * @param dto
     * @return
     */
    private GridDto paddingField(GridDto dto) {
        if (dto != null) {
            if (dto.getVillageId() != null) {
                VillageDto villageDto = villageService.selectCacheById(dto.getVillageId());
                dto.setVillage(villageDto);
            }
        }
        return dto;
    }

    @Override
    public int queryTotal(Map<String, Object> params) {
        return gridDao.queryTotal(params);
    }

    @Override
    public Long save(GridDto dto) {
        GridEntity entity = CopyUtils.copyObj(dto, GridEntity.class);
        entity.setId(Snowflake.nextId());
        gridDao.insert(entity);
        return entity.getId();
    }

    @Override
    public void updateById(GridDto dto) {
        GridEntity entity = CopyUtils.copyObj(dto, GridEntity.class);

        gridDao.updateById(entity);

        CLEAR_CACHE_FUNC.accept(dto);
    }

    @Override
    public void updateAllColumnById(GridDto dto) {
        GridEntity entity = CopyUtils.copyObj(dto, GridEntity.class);

        MyBatisPlusUtils.updateAllColumnById(entity, gridDao);

        CLEAR_CACHE_FUNC.accept(dto);
    }

    @Override
    public void deleteById(Long id) {

        CLEAR_CACHE_FUNC.accept(selectById(id));

        gridDao.deleteById(id);

    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteBatch(Long[] ids) {
        for (Long id : ids) {
            deleteById(id);
        }
        for (Long id : ids) {
            gridBindingDao.delete(new QueryWrapper<GridBindingEntity>()
                    .eq("grid_id", id));
        }
    }
}
